<template>
<div class="page">
  <div class="search">
    <a-form-model :form="form" :label-col="labelCol" :wrapper-col="wrapperCol" @submit.pre.prevent="search">
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="法人行">
            <a-input v-model="form.instId" disabled />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="广告描述">
            <a-input v-model="form.adDesc" placeholder="请输入广告描述" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="上传时间">
            <a-range-picker v-model="form.timeRange"/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="状态">
            <a-select v-model="form.adStatus" placeholder="请选择状态">
              <a-select-option value="">请选择</a-select-option>
              <a-select-option value="02">待发布</a-select-option>
              <a-select-option value="01">已发布</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" style="text-align: center;">
          <a-space>
            <a-button type="primary" html-type="submit">查询</a-button>
            <a-button @click="reset">重置</a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
  <div class="operation">
    <a-space>
      <a-button type="primary" icon="plus" @click="add" v-has-permission="['marketingAds:add']">新增</a-button>
    </a-space>
  </div>
  <a-table
    class="scrollable"
    ref="table"
    :columns="columns"
    :dataSource="dataSource"
    :rowKey="(record, index) => index"
    :loading="loading"
    :pagination="pagination"
    @change="pageChange"
    @showSizeChange="pageChange"
    :scroll="{x: true}"
  >
    <template v-slot:operation="text, record">
      <div style="white-space: nowrap">
        <a-icon type="eye" theme="twoTone" twoToneColor="#4a9ff5" @click="view(record)" title="详情" v-has-permission="['marketingAds:view']"></a-icon>
        <a-icon type="setting" theme="twoTone" twoToneColor="#4a9ff5" @click="edit(record)" title="修改"  v-has-permission="['marketingAds:edit']"></a-icon>
        <a-icon type="check-circle" theme="twoTone" twoToneColor="#4a9ff5" @click="release(record)" title="发布" v-has-permission="['marketingAds:release']"></a-icon>
        <a-icon type="delete" theme="twoTone" twoToneColor="red" @click="del(record)" title="删除" v-has-permission="['marketingAds:delete']"></a-icon>
      </div>
    </template>
  </a-table>
  <marketingAds-operation ref="marketingAdsOperation" @refresh="fetch"></marketingAds-operation>
</div>
</template>

<script>
import {mapState} from 'vuex'
import MarketingAdsOperation from '@/views/bizimpl/upmp/merParam/marketingAds/MarketingAdsOperation'
import moment from 'moment'

export default {
  name: 'MarketingAds',
  components: {
    MarketingAdsOperation
  },
  data() {
    return {
      form: {
        instId: '',
        adDesc: '',
        timeRange: [],
        adStatus: ''
      },
      labelCol: {span: 8},
      wrapperCol: {span: 16},
      loading: false,
      pagination: {
        pageSizeOptions: ['5', '10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      columns:[
        {title: "广告描述", dataIndex: "adDesc"},
        {title: "营销页面地址", dataIndex: "marketingPagePath"},
        {
          title: "广告类型",
          dataIndex: "adType",
          customRender: (text) => {
            return ({
              "00": "商户服务轮播广告",
              "01": "交易成功推送广告",
            }[text]) || ''
          }
        },
        {title: "上传时间", dataIndex: "createTime"},
        {
          title: "生效日期",
          dataIndex: "beginTime",
          customRender(text) {
            return text ? moment(text).format('YYYY-MM-DD'): ''
          }
        },
        {
          title: "失效日期",
          dataIndex: "expireTime",
          customRender(text) {
            return text ? moment(text).format('YYYY-MM-DD'): ''
          }},
        {title: "发布人", dataIndex: "isuId"},
        {title: "发布时间", dataIndex: "isuTm"},
        {
          title: "状态",
          dataIndex: "status",
          customRender: (text) => {
            return ({
              "01": "发布",
              "02": "待发布",
              "03": "注销",
            }[text]) || ''
          }
        },
        {
          title: '操作',
          fixed: 'right',
          scopedSlots: {customRender: 'operation'}
        }
      ],
      dataSource:[],
    }
  },
  computed: {
    ...mapState({
      user: state => state.account.user
    })
  },
  methods: {
    search() {
      this.$set(this.pagination, 'current', 1)
      this.fetch()
    },
    async fetch() {
      const params = {
        instId: this.user.instId,
        adDesc: this.form.adDesc,
        adStatus: this.form.adStatus,
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize,
      }
      if (this.form.timeRange.length) {
        params.startTime = this.form.timeRange[0].format('YYYY-MM-DD') + ' 00:00'
        params.endTime = this.form.timeRange[1].format('YYYY-MM-DD') + ' 23:59'
      }
      this.loading = true
      try {
        const res = await this.$get('/admin/merParam/marketingAds/list', params)
        this.dataSource = res.data.records
        this.$set(this.pagination, 'total', res.data.total)
      } catch (e) {
        this.$message.error('查询营销广告失败')
        console.error(e)
      }
      this.loading = false
    },
    resolveBeanInfo(data) {
      const {entity, merchantList, circleList, list1, adType1, orgList} = data
      return {
        instId: this.user.instId,
        status: entity.status,
        optFlag: entity.optFlag,
        adType: entity.adType,
        marketingPagePath: entity.marketingPagePath,
        beginTime: entity.beginTime,
        expireTime: entity.expireTime,
        orgList: orgList || [],
        adDesc: entity.adDesc,
        mainDataId: entity.mainDataId,
        merchantNoRows: (merchantList && merchantList.replace(/,/g,'\n')) || '',
        merchantCircleRows: (circleList && circleList.replace(/,/g,'\n')) || '',
        pushAdModule: entity.pushAdModule,
        imagesInfo: list1,
        hasUploaded: false,
        adType1: adType1, // 旧平台代码  意义不明
      }
    },
    async add() {
      const hideLoading = this.$message.loading('加载中...', 0);
      try {
        const res = await this.$get('admin/merParam/marketingAds/edit', {optFlag: 'add', instId: this.user.instId});
        const {entity} = res.data
        this.$refs.marketingAdsOperation.show('add', {
          instId: this.user.instId,
          status: entity.status,
          optFlag: entity.optFlag,
        })
      } catch (e) {
          console.error(e)
      }
      hideLoading()
    },
    async edit(record) {
      const hideLoading = this.$message.loading('加载中...', 0);
      try {
        const res = await this.$get('admin/merParam/marketingAds/edit', {
          optFlag: 'upd',
          instId: this.user.instId,
          adType: record.adType,
          marketingPagePath: record.marketingPagePath,
          mainDataId: record.mainDataId,
        });
        this.$refs.marketingAdsOperation.show('edit', this.resolveBeanInfo(res.data))
      } catch (e) {
        console.error(e)
      }
      hideLoading()
    },
    async view (record) {
      const hide = this.$message.loading("加载中...", 0);
      try {
        const res = await this.$get('/admin/merParam/marketingAds/edit', {
          instId: this.user.instId,
          adType: record.adType,
          marketingPagePath: record.marketingPagePath,
          mainDataId: record.mainDataId,
          optFlag: 'view'
        })
        this.$refs.marketingAdsOperation.show('view', this.resolveBeanInfo(res.data))
      } catch (e) {
        console.error(e)
      }
      hide()
    },
    del (record) {
      this.$confirm({
        title: '提示',
        content: '确定删除该营销广告吗？',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          const hideLoading = this.$message.loading('删除中...', 0);
          this.$post('admin/merParam/marketingAds/delete', {
            instId: this.user.instId,
            adType: record.adType,
            mainDataId: record.mainDataId,
          }).then(res => {
            if (res.data.code === '100000') {
              this.$message.success('删除成功')
              this.fetch()
            } else {
              this.$message.error(res.data.message)
            }
          }).catch(e => {
            console.error(e)
            this.$message.error('删除失败')
          }).finally(hideLoading)
        }
      })
    },
    async release (record) {
      if (record.status === '01') {
        this.$message.error('该营销广告已发布，不能重复发布')
        return
      }
      const hide = this.$message.loading("加载中...", 0);
      try {
        const res = await this.$get('/admin/merParam/marketingAds/edit', {
          instId: this.user.instId,
          adType: record.adType,
          marketingPagePath: record.marketingPagePath,
          mainDataId: record.mainDataId,
          optFlag: 'release'
        })
        this.$refs.marketingAdsOperation.show('release', this.resolveBeanInfo(res.data))
      } catch (e) {
        console.error(e)
      }
      hide()
    },
    reset() {
      this.form = {
        instId: this.user.instId,
        adDesc: '',
        timeRange: [],
        adStatus: ''
      }
      this.search()
    },
    pageChange (e) {
      this.pagination.current = e.current;
      this.pagination.pageSize = e.pageSize;
      this.fetch();
    }
  },
  mounted () {
    this.$set(this.form, 'instId', this.user.instId)
    this.search()
  }
}
</script>

<style scoped>
.operation {
  margin-bottom: 10px;
}
.page {
  width: 100%;
}
/deep/ .scrollable .ant-table td {
  white-space: nowrap;
}
</style>
